#!/bin/bash

# Session name
SESSION_NAME="pnp_tmux"

# Check if the tmux session already exists
tmux has-session -t $SESSION_NAME 2>/dev/null
if [ $? != 0 ]; then
  # Create a new tmux session
  tmux new-session -d -s $SESSION_NAME

  # Step 1: Create 4 layout
  tmux split-window -h    # Split vertically to create two columns
  tmux split-window -v    # Split the left column into two rows
  tmux select-pane -t 0   # Go back to the first pane
  tmux split-window -v    # Split the right column into two rows

  # Step 2: Split the first pane vertically
  tmux select-pane -t 0   # Go back to the last pane (top-left)
  tmux split-window -h    # Split the first pane vertically

  # Step 2: Split the first pane vertically
  tmux select-pane -t 1   # Go back to the last pane (top-left)
  tmux split-window -h    # Split the first pane vertically
  
  # Step 3: Arrange the layout for better visualization
  tmux select-layout tiled  # Ensure the layout adjusts cleanly
  
  # Send commands to each pane with proper delays
  tmux send-keys -t $SESSION_NAME:0.0 '1' C-m 
  tmux send-keys -t $SESSION_NAME:0.1 '1' C-m
  tmux send-keys -t $SESSION_NAME:0.2 '1' C-m
  tmux send-keys -t $SESSION_NAME:0.3 '1' C-m && sleep 2
  tmux send-keys -t $SESSION_NAME:0.4 '2' C-m 
  tmux send-keys -t $SESSION_NAME:0.5 '2' C-m && sleep 2
  
  tmux send-keys -t $SESSION_NAME:0.0 'roslaunch realsense2_camera rs_D455_A.launch' C-m && sleep 3
  tmux send-keys -t $SESSION_NAME:0.1 'roslaunch multi_camera_cooperation camA_pnp_target_node_ros_test.launch' C-m
  tmux send-keys -t $SESSION_NAME:0.2 'rqt_image_view'
  tmux send-keys -t $SESSION_NAME:0.3 'loadparam'
  tmux send-keys -t $SESSION_NAME:0.4 'loadbridge'
  tmux send-keys -t $SESSION_NAME:0.5 'ros2 launch ftservocontrol ServoControl.launch.py'
fi

# Attach to the session
tmux attach-session -t $SESSION_NAME
